

package GUI;

/**
 *
 * @author David Ponce
 * @author Philipp Armbruster
 */


import Interaction.ServerConnection;
import Flightadministration.Flightadministration;
import Data.*;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;


public class FlightCreate extends JPanel{

    final Main td;
    private JPanel jp;
    private DateFormat uhrformatter;
    private DateFormat uhrformatter2;
    public Vector<Airport> allAirports;
    public Vector<String> allAirportCitiesAndIds;
    public Vector<Airline> allAirlines;
    public Vector<String> allAirlineNames;
    public DefaultComboBoxModel model1;
    public DefaultComboBoxModel model2;
    public DefaultComboBoxModel model3;
    public JComboBox comboBox3;
    public JComboBox comboBox4;
    public JComboBox comboBox5;
    /*Das AdministrationsObjekt, welches über die getConnection methode vom RMI Server geholt wird, dem "admin" objekt zugewiesen.
    *Dadurch ist eine Kommunikation zwischen GUI und Applikationsserver mittels RMI möglich*/
    final Flightadministration admin = ServerConnection.getConnection();


    // Konstruktor
    public FlightCreate(final Main td) throws RemoteException {
        
        this.td = td;
        showFlightCreate();
    }

    
    // Methoden
    public void showFlightCreate() throws RemoteException {

        jp = new JPanel();

        //GridBagLayout
        //**********************************************************************
        
        GridBagLayout gbl = new GridBagLayout();
        jp.setLayout(gbl);
        jp.setBackground(Color.white);

        GridBagConstraints constraints = new GridBagConstraints();

        constraints.fill = GridBagConstraints.HORIZONTAL;   // wie Komponente Bereich füllen soll
        constraints.weightx = 1;                     // Breite
        constraints.weighty = 1;                    // Höhe
        constraints.insets = new Insets(0,0,1,1);   // Abstände definieren


        //Label
        //**********************************************************************

        JLabel headline = new JLabel("<html><h2 color=blue>Flug anlegen</h2></html>");
        headline.setHorizontalAlignment(JLabel.CENTER);
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.gridwidth = 4;
        jp.add(headline, constraints);

        JLabel label2 = new JLabel("Abflugstag/-uhrzeit festlegen: ");
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 1;
        jp.add(label2, constraints);

        // Vector erzeugen und alle Wochentag hinzufügen
        final Vector<String> weekdays = new Vector<String>();
            weekdays.add("Bitte auswählen");
            weekdays.add("Montag");
            weekdays.add("Dienstag");
            weekdays.add("Mittwoch");
            weekdays.add("Donnerstag");
            weekdays.add("Freitag");
            weekdays.add("Samstag");
            weekdays.add("Sonntag");


        final JComboBox comboBox1 = new JComboBox(weekdays) ;
        constraints.gridx = 1;
        constraints.gridy = 1;
        jp.add(comboBox1, constraints);

        final SpinnerDateModel abflugSpinner = new SpinnerDateModel(new Date(), null, null, Calendar.HOUR_OF_DAY);
        final JSpinner spinner = new JSpinner(abflugSpinner);
        constraints.gridx = 1;
        constraints.gridy = 2;
        uhrformatter = new SimpleDateFormat("HH:mm");
        uhrformatter.format(new Date());
        spinner.setEditor(new JSpinner.DateEditor(spinner, "HH:mm"));
        jp.add(spinner, constraints);

        JLabel label3 = new JLabel("Ankunftstag/-uhrzeit festlegen: ");
        constraints.gridx = 0;
        constraints.gridy = 3;
        jp.add(label3, constraints);

        final JComboBox comboBox2 = new JComboBox(weekdays) ;
        constraints.gridx = 1;
        constraints.gridy = 3;
        jp.add(comboBox2, constraints);

        final SpinnerDateModel ankunftsSpinner = new SpinnerDateModel(new Date(), null, null, Calendar.MINUTE);
        JSpinner spinner2 = new JSpinner(ankunftsSpinner);
        constraints.gridx = 1;
        constraints.gridy = 4;
        uhrformatter2 = new SimpleDateFormat("HH:mm");
        uhrformatter2.format(new Date());
        spinner2.setEditor(new JSpinner.DateEditor(spinner2, "HH:mm"));
        jp.add(spinner2, constraints);

        JLabel label4 = new JLabel("Abflughafen auswählen: ");
        constraints.gridx = 2;
        constraints.gridy = 2;
        jp.add(label4, constraints);

        // Vector mit allen Flughäfen aus der Datenbank befüllen
        allAirports = admin.getAllAirportsForComboBox();
        // Vector mit Flughafenbezeichnungen aus der Datenbank befüllen
        allAirportCitiesAndIds = admin.getAllAirportCitiesAndIdsForComboBox();
        // Neue Models für die ComboBoxen erzeugen und die Flughafenbezeichnungen übergeben
        model1 = new DefaultComboBoxModel(allAirportCitiesAndIds);
        model2 = new DefaultComboBoxModel(allAirportCitiesAndIds);

        comboBox3 = new JComboBox();
        comboBox3.setModel(model1);
        constraints.gridx = 3;
        constraints.gridy = 2;
        jp.add(comboBox3, constraints);

        JLabel label5 = new JLabel("Zielflughafen auswählen: ");
        constraints.gridx = 2;
        constraints.gridy = 3;
        jp.add(label5, constraints);

        comboBox4 = new JComboBox() ;
        comboBox4.setModel(model2);
        constraints.gridx = 3;
        constraints.gridy = 3;
        jp.add(comboBox4, constraints);

        // Vector mit allen Fluglinien aus der Datenbank befüllen
        allAirlines = admin.getAllAirlinesForComboBox();
        // Vector mit Namen aller Fluglinien aus der Datenbank befüllen
        allAirlineNames = admin.getAllAirlineNamesForComboBox();
        // Neues Model für die ComboBox erzeugen und die Fluglinienbezeichnungen übergeben
        model3 = new DefaultComboBoxModel(allAirlineNames);

        JLabel label6 = new JLabel("Fluglinie auswählen: ");
        constraints.gridx = 2;
        constraints.gridy = 1;
        jp.add(label6, constraints);

        comboBox5 = new JComboBox();
        comboBox5.setModel(model3);
        constraints.gridx = 3;
        constraints.gridy = 1;
        jp.add(comboBox5, constraints);


        //Buttons
        //**********************************************************************

        JButton button_CreateFlight = new JButton("Flug anlegen");
        constraints.gridx = 0;
        constraints.gridy = 6;
        constraints.gridwidth = 2;
        jp.add(button_CreateFlight, constraints);

        JButton button_Cancel = new JButton("Zurück zur Übersicht");
        constraints.gridx = 2;
        constraints.gridy = 6;
        constraints.gridwidth = 2;
        jp.add(button_Cancel, constraints);


        //Action Listener
        //**********************************************************************
        
        button_CreateFlight.addActionListener(new ActionListener() {
                @Override
        public void actionPerformed(ActionEvent e) {
                    if ((comboBox1.getSelectedItem().equals("Bitte auswählen"))
                            || (comboBox2.getSelectedItem().equals("Bitte auswählen"))
                            || (comboBox3.getSelectedItem().equals("Bitte auswählen"))
                            || (comboBox4.getSelectedItem().equals("Bitte auswählen"))
                            || (comboBox5.getSelectedItem().equals("Bitte auswählen")))
                    {
                        JOptionPane.showMessageDialog(null, "Bitte alle Felder ausfüllen!");
                        return;
                    }

                    Object sourceAirport = comboBox3.getSelectedItem();
                    Object targetAirport = comboBox4.getSelectedItem();
                    if (sourceAirport.equals(targetAirport))
                    {
                        JOptionPane.showMessageDialog(null, "<html><p style=\"color:red; text-align: center\">" + 
                                                            "Start- und Zielflughafen dürfen nicht identisch sein!</p></html>");
                        comboBox3.setSelectedIndex(0);
                        comboBox4.setSelectedIndex(0);
                        return;
                    }

                    Date departureTime = abflugSpinner.getDate();
                        int hours1 = departureTime.getHours();
                        int minutes1 = departureTime.getMinutes();
                        int time1 = hours1 + minutes1;

                    Date arrivalTime = ankunftsSpinner.getDate();
                        int hours2 = arrivalTime.getHours();
                        int minutes2 = arrivalTime.getMinutes();
                        int time2 = hours2 + minutes2;

                    if (time1 >= time2)
                    {
                        JOptionPane.showMessageDialog(null, "<html><p style=\"color:red; text-align: center\">" + 
                                                            "Der Ankunftszeitpunkt darf nicht vor dem Abflugzeitpunkt liegen,<br>" +
                                                            "beziehungweise gleich dem Abflugzeitpunkt sein!</p></html>");
                        return;
                    }
                    else {
                        try {

                            Object currenttimeOfDeparture = new SimpleDateFormat( "HH:mm" ).format( abflugSpinner.getDate());
                            String currenttimeOfDepartureString = currenttimeOfDeparture.toString();

                            String currentDayOfDeparture = String.valueOf(comboBox1.getSelectedItem());

                            Object currenttimeOfArrival = new SimpleDateFormat( "HH:mm" ).format( ankunftsSpinner.getDate());
                            String currenttimeOfArrivalString = currenttimeOfArrival.toString();

                            String currentDayOfArrival = String.valueOf(comboBox2.getSelectedItem());

                            String currentAirportOfDeparture = String.valueOf(comboBox3.getSelectedItem());
                                int index1 = currentAirportOfDeparture.indexOf("(") + 1;
                                int index2 = currentAirportOfDeparture.indexOf(")");
                                    String intIdOfDepartureAirport = currentAirportOfDeparture.substring(index1, index2);

                            String currentAirportOfArrival = String.valueOf(comboBox4.getSelectedItem());
                                int index3 = currentAirportOfArrival.indexOf("(") + 1;
                                int index4 = currentAirportOfArrival.indexOf(")");
                                    String intIdOfArrivalAirport = currentAirportOfArrival.substring(index3, index4);

                            // Den Namen der ausgewählten Fluglinie (Airline) aus der Combobox auslesen
                            String currentAirline = String.valueOf(comboBox5.getSelectedItem());
                            int currentAirlineId = 0;
                            // Über eine for-Schleife die Id der Fluglinie auslesen und in die Variable 'currentAirlineId' speichern
                            for(int i = 0; i<allAirlines.size(); i++) {
                                if(allAirlines.get(i).getAirName().equals(currentAirline)) {
                                    currentAirlineId = allAirlines.get(i).getAirId();
                                }
                            }

                            // Flug anlegen und in Datenbank speichern
                            admin.createFlight(currenttimeOfDepartureString, currentDayOfDeparture, currenttimeOfArrivalString,
                                    currentDayOfArrival, intIdOfDepartureAirport, intIdOfArrivalAirport, currentAirlineId);

                                // JTables aktualisieren
                                td.updateFlight();

                            JOptionPane.showMessageDialog(null, "Flug angelegt");

                            ((CardLayout) td.rightp.getLayout()).show(td.rightp, "FlightM");

                            comboBox1.setSelectedIndex(0);
                            comboBox2.setSelectedIndex(0);
                            comboBox3.setSelectedIndex(0);
                            comboBox4.setSelectedIndex(0);
                            comboBox5.setSelectedIndex(0);

                        } catch (RemoteException ex) {
                            Logger.getLogger(AircraftCreate.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
       }});

       button_Cancel.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                     ((CardLayout) td.rightp.getLayout()).show(td.rightp,"FlightM");

            }
        });
    }

    public void updateVectorForAllAirportCitiesAndIds(Vector<String> allAirportCitiesAndIds) {
        this.allAirportCitiesAndIds = allAirportCitiesAndIds;
    }

    public void updateVectorAllAirports(Vector<Airport> allAirports) {
        this.allAirports = allAirports;
    }
    
    public JPanel getJp() {
        return jp;
    }

}
